/**
 * Created by daigou on 2015/6/1.
 */
var http = require('http');
var config = require('./config.json');

function setProduct(product, item) {
    var request = http.request(config.apiOption, function (res) {
        res.setEncoding('utf8');
        var data = '';
        res.on('data', function (chunk) {
            data += chunk;
        }).on('end', function () {
            data = JSON.parse(data);
        });
    });

    var data = {
        method: 'ProductReview.ReviewProduct',
        id: 65535,
        params: {
            obj: getReviewInfo()
        }
    };

    request.write(JSON.stringify(data), 'utf8');
    request.end();

    function getReviewInfo() {
        var raty = Math.ceil((item.userStar || 0) / 2);
        var skus = [];
        for (var key in item.skuMap) {
            skus.push(key + ':' + item.skuMap[key]);
        }
        var pictures=(item.feedPicPathList||[]).map(function (item) {
           return convertToAbsoluteUrl(item);
        });

        return {
            productUrl: product.url,
            userID: 0,
            rating: raty > 0 ? raty : 1,
            comment: item.feedback,
            pictures: pictures,
            sku: skus.join(';'),
            nickName: item.userNick,
            createDate: item.feedbackDate,
            profilePic: convertToAbsoluteUrl(item.headPicUrl)
        };
    }
}

function batchSaveProduct(product, data) {
    data.forEach(function (item) {
        setProduct(product, item);
    });
}

function convertToAbsoluteUrl(src) {
    return src.indexOf('http:') >= 0 ? src : 'http:' + src;
}

module.exports = batchSaveProduct;